package com.xiangyu.demo.configuration;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;

import java.lang.reflect.Method;

/**
 * java类简单作用描述
 *
 * @ProjectName: springboot-demo
 * @Package: com.xiangyu.demo.configuration
 * @Description: java类作用描述
 * @Author: 向羽
 * @CreateDate: 2018/1/22 13:51
 * @UpdateUser: 向羽
 * @UpdateDate: 2018/1/22 13:51
 * @UpdateRemark: The modified content
 * @Version: 2.0
 */
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {

    @Value("${com.xiangyu.blog.redis_timeout}")
    private String redisTimeout;

    /**
     * @Author: 向羽
     * @Description: 在使用@Cacheable时，如果不指定key，则使用找个默认的key生成器生成的key
     * @Date: 2018/1/22 14:17
     */
   /* @Override
    public KeyGenerator keyGenerator() {
        return (target,method,params)->{
            StringBuilder sb = new StringBuilder();
            sb.append(target.getClass().getName());
            sb.append(".").append(method.getName());

            StringBuilder paramsSb = new StringBuilder();
            for (Object param : params) {
                // 如果不指定，默认生成包含到键值中
                if (param != null) {
                    paramsSb.append(param.toString());
                }
            }

            if (paramsSb.length() > 0) {
                sb.append("_").append(paramsSb);
            }
            return sb.toString();
        };
    }*/
    @Override
    public KeyGenerator keyGenerator() {
        return new KeyGenerator() {
            @Override
            public Object generate(Object o, Method method, Object... objects) {
                StringBuilder sb = new StringBuilder();
                sb.append(o.getClass().getName());
                sb.append(method.getName());
                for (Object obj : objects) {
                    sb.append(obj.toString());
                }
                return sb.toString();
            }
        };
    }


    //缓存管理器
//    为了实现cache注解支持过期时间，提供以下两种方法
    // 1.修改CacheManager设置对应缓存名称的过期时间
    // 2.扩展CacheManager实现参数化设置过期时间：如
    @Bean
    public CacheManager cacheManager(RedisTemplate redisTemplate) {
        RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate);
        //设置缓存过期时间
        cacheManager.setDefaultExpiration(Long.valueOf(redisTimeout));
        return cacheManager;
    }

    /**
     * 数据序列化为json格式，key必须为string类型
     *
     * @param factory
     * @return
     */
    @Bean
    public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
        StringRedisTemplate template = new StringRedisTemplate(factory);
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        template.setValueSerializer(jackson2JsonRedisSerializer);
        template.afterPropertiesSet();
        return template;
    }


}
